package com.hut.oa.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.mail.Session;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hut.oa.model.bean.Attachment;
import com.hut.oa.model.bean.EmailManage;
import com.hut.oa.model.bean.Status;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.dao.AttachmentDao;
import com.hut.oa.model.dao.mail.MailDao;
import com.hut.oa.model.dao.system.StatusDao;
import com.hut.oa.model.dao.user.UserDao;
import com.hut.oa.service.AttachmentService;
import com.hut.oa.service.EmailService;
import com.hut.oa.service.SystemService;

@Controller
@RequestMapping("/mail")
public class MailController {
	@Autowired
	private AttachmentDao acdao;
	@Autowired
	private StatusDao statudao;

	@Autowired
	private UserDao udao;

	@Autowired
	private MailDao mdao;

	@Autowired
	private EmailService emaiservice;
	
	@Autowired
	private AttachmentService attservice;
	
	@Autowired
	private SystemService ss;
	@RequestMapping
	public String toMail(HttpSession session, Model model,@PageableDefault(value = 8, sort = { "emId" }) Pageable pageable) {
		User u = (User) session.getAttribute("userinfo");		
		Page<EmailManage> maillist = mdao.findByGetuserAndEmEsIdAndEmIsDelete(pageable,u, 0l,0);		
		model.addAttribute("maillist", maillist);
		model.addAttribute("box","0");
		model.addAttribute("href","/mail/getbox");
		model.addAttribute("status", ss.statusDatas.get("email_manage"));
		List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
		model.addAttribute("mailnum", list.size());
		return "mail/mail";
	}

	/**
	 * 发件箱信息更新
	 */
	@RequestMapping("/sendbox")
	public String sendbox(Model model, HttpSession session,@PageableDefault(value = 8, sort = { "emId" }) Pageable pageable) {
		User u = (User) session.getAttribute("userinfo");
		Page<EmailManage> ulist = mdao.findBySenduserAndEmEsIdAndEmIsDelete(pageable,u, 1l,0);
		model.addAttribute("maillist", ulist);
		model.addAttribute("box","1");
		model.addAttribute("href","/mail/sendbox");
		model.addAttribute("status", ss.statusDatas.get("email_manage"));
		List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
		model.addAttribute("mailnum", list.size());
		return "mail/mail";
	}

	/**
	 * 收件箱信息更新
	 */
	@RequestMapping("/getbox")
	public String getbox(Model model, HttpSession session,@PageableDefault(value = 8, sort = { "emId" }) Pageable pageable) {
		User u = (User) session.getAttribute("userinfo");
		Page<EmailManage> maillist = mdao.findByGetuserAndEmEsIdAndEmIsDelete(pageable,u, 0l,0);
		model.addAttribute("maillist", maillist);
		model.addAttribute("box","0");
		model.addAttribute("href","/mail/getbox");
		model.addAttribute("status", ss.statusDatas.get("email_manage"));
		List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
		model.addAttribute("mailnum", list.size());
		return "mail/mail";
	}
	/**
	 * 草稿箱信息更新
	 */
	 @RequestMapping("/graftbox")
		public String graftbox(Model model, HttpSession session,@PageableDefault(value = 8, sort = { "emId" }) Pageable pageable) {
			User u = (User) session.getAttribute("userinfo");
			Page<EmailManage> maillist = mdao.findBySenduserAndEmEsIdAndEmIsDelete(pageable,u, 2l,0);
			model.addAttribute("maillist", maillist);
			model.addAttribute("box","1");
			
			model.addAttribute("href","/mail/graftbox");
			model.addAttribute("status", ss.statusDatas.get("email_manage"));
			List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
			model.addAttribute("mailnum", list.size());
			return "mail/mail";
		}
	 /**
	  * 垃圾箱信息刷新
	  */
	 @RequestMapping("/garbage")
		public String garbage(Model model, HttpSession session,@PageableDefault(value = 8, sort = { "emId" }) Pageable pageable) {
			User u = (User) session.getAttribute("userinfo");
			Page<EmailManage> maillist = mdao.findgabege(pageable, u.getId());
			model.addAttribute("maillist", maillist);
			model.addAttribute("box","2");
			model.addAttribute("href","/mail/garbage");
			model.addAttribute("status", ss.statusDatas.get("email_manage"));
			List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
			model.addAttribute("mailnum", list.size());
			return "mail/mail";
		}
	 /**
	  * 星标邮件
	  */
	 @RequestMapping("/emailstar")
		public String emailstar(Model model, HttpSession session,@PageableDefault(value = 8, sort = { "emId" }) Pageable pageable) {
			User u = (User) session.getAttribute("userinfo");
			Page<EmailManage> maillist = mdao.findstaremail(pageable,u.getId());
			System.out.println(maillist.getContent());
			model.addAttribute("maillist", maillist);
			model.addAttribute("box","3");
			model.addAttribute("href","/mail/emailstar");
			model.addAttribute("status", ss.statusDatas.get("email_manage"));
			List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
			model.addAttribute("mailnum", list.size());
			return "mail/mail";
		}
	/**
	 * 到添加邮件页面
	 * 
	 * @return
	 */
	@RequestMapping("/addmail")
	public String toAddFile(Model model, HttpSession session) {
		User u = (User) session.getAttribute("userinfo");

		List<Status> statulist = statudao.findByModule("email_manage");
		List<User> ulist = udao.findByIdNot(u.getId());
		model.addAttribute("userlist", ulist);
		model.addAttribute("statuslist", statulist);
		
		return "mail/addMail";
	}
	
	/**
	 * 设置星标
	 */
	@RequestMapping(value="/setstart",method = RequestMethod.POST)
	@ResponseBody
	public void setstart(Model model, HttpSession session,@RequestParam("dataid")String dataid,@RequestParam("type")String type) {
			if(type.trim().equals("收藏")){
				//1代表收藏
				emaiservice.updatestar(Long.parseLong(dataid),1);
			}else if(type.trim().equals("取消")){
				//0取消收藏
				emaiservice.updatestar(Long.parseLong(dataid),0);
			}
	}
	/**
	 * 删除多个
	 */
	@RequestMapping(value="/deletemany",method = RequestMethod.POST)
	@ResponseBody
	public void deletemany(@RequestParam("many")String[] many,@RequestParam("box")String box) {	
			for (int i = 0; i < many.length; i++) {
				if(box.equals("垃圾箱")){
					emaiservice.puredelte(Long.parseLong(many[i]));
				}else{
					emaiservice.deleteid(Long.parseLong(many[i]));
				}	
			}
			
	}
	/**
	 * 设置所有星标
	 */
	
	@RequestMapping(value="/setallstart",method = RequestMethod.POST)
	public void setallstart(@RequestParam("type")String type, HttpSession session,@RequestParam("many")String[] many) {
		User u=(User) session.getAttribute("userinfo");
		for (int i = 0; i < many.length; i++) {
			if(type.trim().equals("收藏")){				
				emaiservice.updatestar(Long.parseLong(many[i]),1);
			}else if(type.trim().equals("取消")){
				emaiservice.updatestar(Long.parseLong(many[i]),0);
			}
		}		
	}
	/**
	 * 发送邮件
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "/sendemail", method = RequestMethod.POST)
	@ResponseBody
	public void sendemail(Model model, HttpSession session, @RequestParam("statustype") String statustype,
			@RequestParam("tittle") String tittle, @RequestParam("userid") String userid,
			@RequestParam("content") String content, @RequestParam("username") String username,
			@RequestParam("type") String type,@RequestParam("attid") String attid){
		
		User u = (User) session.getAttribute("userinfo");
		User getu = new User();	
		EmailManage sendmail = new EmailManage();
		sendmail.setEmContent(content);
		sendmail.setEmTitle(tittle);
		sendmail.setEmTime(new Date());
		sendmail.setSenduser(u);
		sendmail.setEmStatus(Long.parseLong(statustype));
		if (type.trim().equals("草稿")) {
			sendmail.setEmEsId(2l);
		} else if (type.trim().equals("发送")) {
			sendmail.setEmEsId(1l);
		}
		if(attid.equals("undefined")){		
		}else{
			sendmail.setAttid(Long.parseLong(attid));
		}
		// 0代表收件1发件2草稿3垃圾
		sendmail.setEmgetusername(username);
		sendmail.setEmgetuserid(userid);
		mdao.save(sendmail);
		if (type.trim().equals("发送")) {
			String[] id = userid.split("、");
			for (int i = 0; i < id.length; i++) {
				EmailManage mail = new EmailManage();
				getu.setId(Long.parseLong(id[i]));
				mail.setEmTitle(tittle);
				mail.setEmTime(new Date());
				mail.setSenduser(u);
				mail.setGetuser(getu);
				mail.setEmContent(content);
				mail.setEmStatus(Long.parseLong(statustype));
				mail.setEmEsId(0l);
				if(attid.equals("undefined")){				
				}else{
					mail.setAttid(Long.parseLong(attid));
				}
				mdao.save(mail);
			}
		}
	}
	
	/**
	 * 添加附件
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value="/uploadfile",method = RequestMethod.POST)
	@ResponseBody
	public	Long uploadfile(@RequestParam("file")MultipartFile file,HttpSession session) throws IllegalStateException, IOException {
		User u=(User) session.getAttribute("userinfo");
		Attachment	att=attservice.saveAttachment(file, u.getId(),"emailmanage");
		att.setBusinessId(u.getId());
		acdao.save(att);
		return att.getId();
	}
	/**
	 * 编辑跳转界面
	 */
	@RequestMapping(value="/edit")
	public String edit(HttpSession session,@RequestParam("id")String id,Model model) throws IllegalStateException, IOException {
		User u=(User) session.getAttribute("userinfo");	
		EmailManage email=mdao.findByEmIdAndSenduser(Long.parseLong(id), u);
		model.addAttribute("emailgetuserid",email.getEmgetuserid());
		model.addAttribute("emailgetusername",email.getEmgetusername());
		model.addAttribute("emailtitle",email.getEmTitle());
		model.addAttribute("emailuserstatus",email.getEmStatus());
		model.addAttribute("emailcontent",email.getEmContent());
		model.addAttribute("show", "show");
		//添加附件
		if(email.getAttid()==0){	
		}else{
			Attachment att=acdao.findOne(email.getAttid());
			model.addAttribute("attname",att.getName());
			model.addAttribute("attid", att.getId());
		}
		
		List<Status> statulist = statudao.findByModule("email_manage");
		List<User> ulist = udao.findByIdNot(u.getId());		
		model.addAttribute("userlist", ulist);
		model.addAttribute("statuslist", statulist);
		List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
		model.addAttribute("mailnum", list.size());
		return "mail/addMail";
	}
	/**
	 * 附件下载
	 */
	@RequestMapping(value ="/download/**", method = RequestMethod.GET)
	public void download(HttpServletResponse response,@RequestParam("attid") String id){
		Attachment att=acdao.findOne(Long.parseLong(id));
		attservice.dowloadAtt(att, response);
	}
	/**
	 * 跳转查看界面
	 */
	@RequestMapping(value ="/view")
	public String view(@RequestParam("id")String id,HttpSession session,Model model){
		User u=(User)session.getAttribute("userinfo");	
		EmailManage email=mdao.findByEmIdAndGetuser(Long.parseLong(id),u);
		email.setEmIsRead(1);
		mdao.save(email);
		if(!StringUtils.isEmpty(email.getEmTitle())){
			model.addAttribute("emailtitle",email.getEmTitle());
		}
		model.addAttribute("emailcontent", email.getEmContent());
		model.addAttribute("emailsenduser",email.getSenduser().getName());
		model.addAttribute("emailtime", email.getEmTime());
		model.addAttribute("emailsenduserid", email.getSenduser().getId());
		if(email.getAttid()==0){	
		}else{
			Attachment att=acdao.findOne(email.getAttid());
			model.addAttribute("attname",att.getName());
			model.addAttribute("attid", att.getId());
		}
		List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
		model.addAttribute("mailnum", list.size());
		
		return "/mail/viewMail";
		
	}
	/**
	 * 查看回复
	 */
	@RequestMapping(value ="/viewback", method = RequestMethod.POST)
	public void viewback(HttpSession session,@RequestParam("senduserid") String senduserid,@RequestParam("content") String content){
		User u=(User)session.getAttribute("userinfo");	
		EmailManage getemail=new EmailManage();
		//插入接收方
		getemail.setEmTime(new Date());
		getemail.setEmContent(content);
		getemail.setEmEsId(0l);		
		getemail.setSenduser(u);
		getemail.setGetuser(udao.findOne(Long.parseLong(senduserid)));
		mdao.save(getemail);
		
		//插入发送方
		EmailManage sendemail=new EmailManage();
		sendemail.setEmTime(new Date());
		sendemail.setEmContent(content);
		sendemail.setEmEsId(1l);		
		sendemail.setSenduser(u);
		sendemail.setGetuser(udao.findOne(Long.parseLong(senduserid)));
		mdao.save(sendemail);
	}
	
	@RequestMapping(value ="/fullreback")
	public String fullreback(Model model,HttpSession session,@RequestParam("sendid")String sendid,@RequestParam("senduser")String senduser){
		User u = (User) session.getAttribute("userinfo");
		List<Status> statulist = statudao.findByModule("email_manage");
		List<User> ulist = udao.findByIdNot(u.getId());
		model.addAttribute("userlist", ulist);
		model.addAttribute("statuslist", statulist);		
		model.addAttribute("emailgetusername", senduser);
		model.addAttribute("emailgetuserid", sendid);	
		List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
		model.addAttribute("mailnum", list.size());
		return "/mail/addmail";
		
	}
	@RequestMapping(value ="/manyisread")
	public void manyisread(Model model,@RequestParam("many")String[] many){
		for (int i = 0; i < many.length; i++) {
			emaiservice.isread(Long.parseLong(many[0]));
		}			
	}
	//查找不同类型的邮件
	@RequestMapping(value ="/search")
	public String searchvalue(Model model,HttpSession session,@RequestParam("type")String type,@RequestParam("value")String value,@PageableDefault(value = 4, sort = { "emId" }) Pageable pageable){
		User u=(User) session.getAttribute("userinfo");
		List<EmailManage> list=mdao.findByGetuserAndEmEsIdAndEmIsDeleteAndEmIsRead(u,0l,0,0);
		model.addAttribute("mailnum", list.size());
		if(type.equals("getbox")){
			Page<EmailManage> maillist =mdao.findgetboxbyname(pageable, u.getId(), value);
			model.addAttribute("maillist", maillist);
			model.addAttribute("box","0");
			model.addAttribute("href","/mail/getbox");
			return "mail/mail";
		}else if(type.equals("sendbox")){
			Page<EmailManage> maillist =mdao.findsendboxbyname(pageable, u.getId(), value,1L);
			model.addAttribute("maillist", maillist);
			model.addAttribute("box","1");
			model.addAttribute("href","/mail/sendbox");
			return "mail/mail";
		
		}else if(type.equals("graftbox")){
			Page<EmailManage> maillist =mdao.findsendboxbyname(pageable,u.getId(), value,2L);
			model.addAttribute("maillist", maillist);
			model.addAttribute("box","1");
			model.addAttribute("href","/mail/sendbox");
			return "mail/mail";
		}else if(type.equals("garbage")){
			Page<EmailManage> maillist = mdao.findgabegeboxbyname(pageable,u.getId(),value);
			model.addAttribute("maillist", maillist);
			model.addAttribute("box","1");
			model.addAttribute("href","/mail/graftbox");
			return "mail/mail";
		}else{
			Page<EmailManage> maillist = mdao.findstaremailbytittle(pageable,u.getId(),value);
			System.out.println(maillist.getContent());
			model.addAttribute("maillist", maillist);
			model.addAttribute("box","3");
			model.addAttribute("href","/mail/emailstar");
			return "mail/mail";
		}
		
		
	}
}
